#include <asm-generic/errno-base.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

/*
 * 实现复制功能
 * 添加信号机制
 * */

#define BUFFSIZE 1024

int main(int argc, char **argv)
{
	int input, output;
	char buf[BUFFSIZE];
	int len, ret, pos;
	
	if(argc != 3){
		fprintf(stderr, "Usage.....\n");
		exit(1);
	}

	do{
		input = open(argv[1], O_RDONLY);
		if(input < 0){
			if(errno != EINTR){
				perror("open()");
				exit(1);
			}
		}
	} while(input < 0);

	do{
		output = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0644);
		if(output < 0){
			if(errno != EINTR){
				close(input);
				perror("open()");
				exit(1);
			}
		}
	} while(output < 0);
	
	while(1){
		len = read(input, buf, BUFFSIZE);
		if(len < 0){
			if(errno == EINTR){
				continue;
			}
			perror("read()");
			break;
		} else if(len == 0){
			break;
		}
		pos = 0;
		while(len > 0){
			ret = write(output, buf + pos, len);
			if(ret < 0){
				if(errno == EINTR){
					continue;
				}
				perror("write()");
				exit(1);
			}
			pos += ret; // 记录文件写入位置
			len -= ret; // 一次写不完，继续写入
		}
	}

	close(input);
	close(output);

	exit(0);
}
